﻿using Application.Common.Interfaces;
using Application.Features.Menus.DTOs;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Common.Attributes;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel;

namespace Application.Features.Roles.Queries.GetMenusById;

/// <summary>
/// 查询权限
/// </summary>
[Description("查询权限")]
[GroupDescription(("角色管理"))]
public class GetRoleMenusByRoleIdQuery : IRequest<IEnumerable<MenuOutput>>
{
    public long RoleId { get; set; }
}

public class GetAllMenusQueryHandler :
     IRequestHandler<GetRoleMenusByRoleIdQuery, IEnumerable<MenuOutput>>
{
    private readonly IApplicationDbContext _context;
    private readonly IMapper _mapper;

    public GetAllMenusQueryHandler(
        IApplicationDbContext context,
        IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    public async Task<IEnumerable<MenuOutput>> Handle(GetRoleMenusByRoleIdQuery request, CancellationToken cancellationToken)
    {
        var role = await _context.Roles.SingleOrDefaultAsync(x => x.Id == request.RoleId && x.IsActive);
        if (role == null) return new List<MenuOutput>();

        var query = _context.Menus
            .OrderByDescending(o => o.Meta.Rank)
            .Include(x => x.Meta)
            .Include(rm => rm.RoleMenus)
            .AsNoTracking()
            .AsQueryable();

        query = query.Where(x => x.Meta!.Hidden == false);

        if (!string.Equals("admin", role.RoleCode, StringComparison.OrdinalIgnoreCase))
            query = query.Where(x => x.RoleMenus.Any(rm => rm.RoleId == request.RoleId));

        return await query.ProjectTo<MenuOutput>(_mapper.ConfigurationProvider).ToListAsync();
    }
}